package xyz.zcq.example.consumer;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import xyz.zcq.example.common.model.User;
import xyz.zcq.example.common.service.UserService;
import xyz.zcq.zcqrpc.model.RpcRequest;
import xyz.zcq.zcqrpc.model.RpcResponse;
import xyz.zcq.zcqrpc.serializer.JdkSerializer;
import xyz.zcq.zcqrpc.serializer.Serializer;

import java.io.IOException;

/**
 * 用户服务静态代理
 */
public class UserServiceProxy implements UserService {

    @Override
    public User getUser(User user) {
        // 获取序列化器
        Serializer serializer = new JdkSerializer();
        // 构造RPC请求对象RpcRequest
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .parameters(new Object[]{user})
                .build();
        // 发送请求
        try {
            byte[] reqBody = serializer.serialize(rpcRequest);
            try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080").body(reqBody).execute()) {
                RpcResponse rpcResponse = serializer.deserialization(httpResponse.bodyBytes(), RpcResponse.class);
                return (User) rpcResponse.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
